const Cart = require('../models/Cart')
const Product = require('../models/Product')
const Response = require('../utils/response')
const { validationResult } = require('express-validator')

// 获取购物车列表
exports.getCartList = async (req, res) => {
  try {
    const userId = req.userId
    const cartItems = await Cart.getCartByUserId(userId)
    const stats = await Cart.getCartStats(userId)

    return Response.success(res, {
      items: cartItems,
      stats
    })
  } catch (error) {
    console.error('获取购物车错误:', error)
    return Response.error(res, '获取购物车失败', 500)
  }
}

// 添加商品到购物车
exports.addToCart = async (req, res) => {
  try {
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
      return Response.error(res, errors.array()[0].msg, 400)
    }

    const userId = req.userId
    const { productId, quantity = 1 } = req.body

    // 检查商品是否存在
    const product = await Product.findById(productId)
    if (!product) {
      return Response.notFound(res, '商品不存在')
    }

    // 检查库存
    if (product.stock < quantity) {
      return Response.error(res, '库存不足', 400)
    }

    await Cart.add(userId, productId, quantity)

    return Response.success(res, null, '添加成功')
  } catch (error) {
    console.error('添加购物车错误:', error)
    return Response.error(res, '添加失败', 500)
  }
}

// 更新购物车商品数量
exports.updateCartItem = async (req, res) => {
  try {
    const userId = req.userId
    const { id } = req.params
    const { quantity } = req.body

    if (quantity < 1) {
      return Response.error(res, '数量必须大于0', 400)
    }

    const result = await Cart.updateQuantity(id, userId, quantity)

    if (result.affectedRows === 0) {
      return Response.notFound(res, '购物车商品不存在')
    }

    return Response.success(res, null, '更新成功')
  } catch (error) {
    console.error('更新购物车错误:', error)
    return Response.error(res, '更新失败', 500)
  }
}

// 切换选中状态
exports.toggleSelected = async (req, res) => {
  try {
    const userId = req.userId
    const { id } = req.params
    const { selected } = req.body

    await Cart.toggleSelected(id, userId, selected ? 1 : 0)

    return Response.success(res, null, '操作成功')
  } catch (error) {
    console.error('切换选中状态错误:', error)
    return Response.error(res, '操作失败', 500)
  }
}

// 全选/取消全选
exports.toggleAllSelected = async (req, res) => {
  try {
    const userId = req.userId
    const { selected } = req.body

    await Cart.toggleAllSelected(userId, selected ? 1 : 0)

    return Response.success(res, null, '操作成功')
  } catch (error) {
    console.error('全选操作错误:', error)
    return Response.error(res, '操作失败', 500)
  }
}

// 删除购物车商品
exports.deleteCartItem = async (req, res) => {
  try {
    const userId = req.userId
    const { id } = req.params

    const result = await Cart.delete(id, userId)

    if (result.affectedRows === 0) {
      return Response.notFound(res, '购物车商品不存在')
    }

    return Response.success(res, null, '删除成功')
  } catch (error) {
    console.error('删除购物车商品错误:', error)
    return Response.error(res, '删除失败', 500)
  }
}

// 清空购物车
exports.clearCart = async (req, res) => {
  try {
    const userId = req.userId
    await Cart.clear(userId)

    return Response.success(res, null, '购物车已清空')
  } catch (error) {
    console.error('清空购物车错误:', error)
    return Response.error(res, '清空失败', 500)
  }
}

// 删除选中的商品
exports.deleteSelected = async (req, res) => {
  try {
    const userId = req.userId
    await Cart.deleteSelected(userId)

    return Response.success(res, null, '删除成功')
  } catch (error) {
    console.error('删除选中商品错误:', error)
    return Response.error(res, '删除失败', 500)
  }
}











